package com.yuanlrc.hotel.index;

import com.yuanlrc.common.core.controller.BaseController;
import com.yuanlrc.common.core.domain.AjaxResult;
import com.yuanlrc.hotel.RoomReserve.domain.RoomReserve;
import com.yuanlrc.hotel.RoomReserve.service.IRoomReserveService;
import com.yuanlrc.hotel.account.domain.Account;
import com.yuanlrc.hotel.account.service.IAccountService;
import com.yuanlrc.hotel.rate.service.IRateService;
import com.yuanlrc.hotel.rommType.domain.RoomType;
import com.yuanlrc.hotel.rommType.mapper.RoomTypeMapper;
import com.yuanlrc.hotel.rommType.service.IRoomTypeService;
import com.yuanlrc.hotel.room.domain.Room;
import com.yuanlrc.hotel.room.mapper.RoomMapper;
import com.yuanlrc.hotel.room.service.IRoomService;
import com.yuanlrc.system.utils.SessionUtil;
import org.apache.catalina.manager.util.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/home/index")
public class IndexController extends BaseController {

    @Autowired
    IRoomTypeService roomTypeService;

    @Autowired
    IRoomService roomService;

    @Autowired
    IRoomReserveService roomReserveService;

    @Autowired
    IAccountService accountService;

    @Autowired
    IRateService rateService;


    @RequestMapping("/room")
    public String room(Model model, Integer id)
    {
        List<RoomType> roomTypeList = roomTypeService.selectRoomTypeListAll();
        model.addAttribute("roomTypes", roomTypeList);

        List<Room> rooms = null;

        if(id == null)
        {
            rooms = roomService.selectRoomListNormal();
        }
        else
        {
            rooms = roomService.selectRoomListByRoomTypeId(id);
        }

        for (Room item: rooms) {
            item.setRoomType(roomTypeService.selectRoomTypeById(item.getRoomTypeId().longValue()));
        }

        model.addAttribute("size", rooms.size());
        model.addAttribute("rooms",rooms);
        model.addAttribute("id", id == null ? -1 : id);
        return "home/index/room";
    }

    @RequestMapping("/room_detail")
    public String room_detail(Model model, Integer id)
    {
        Room room = roomService.selectRoomById(id);
        room.setRoomType(roomTypeService.selectRoomTypeById(room.getRoomTypeId().longValue()));

        Double value = rateService.avgRoomRate(room.getId().longValue());
        if(value == null)
            value = 5.0;
        else
        {
            value = Math.floor(value);
        }

        model.addAttribute("room", room);
        model.addAttribute("value",value);

        return "home/index/roomdetail";
    }

    //钟点房显示
    @RequestMapping("/hour_time_room")
    public String hourTimeRoom(Model model, Integer id)
    {
        List<RoomType> roomTypeList = roomTypeService.selectRoomTypeListAll();
        model.addAttribute("roomTypes", roomTypeList);

        List<Room> rooms = null;

        if(id == null)
        {
            rooms = roomService.selectRoomListByHourTimeAll();
        }
        else
        {
            rooms = roomService.selectRoomListByRoomTypeIdAndHourTime(id);
        }

        for (Room item: rooms) {
            item.setRoomType(roomTypeService.selectRoomTypeById(item.getRoomTypeId().longValue()));
        }

        model.addAttribute("size", rooms.size());
        model.addAttribute("rooms",rooms);
        model.addAttribute("id", id == null ? -1 : id);
        return "home/index/hour_time_room";
    }

    //预定
    @RequestMapping("/room_reserve")
    public String roomReserve(Model model, Integer id)
    {
        Account account = SessionUtil.getLogindeAccount();
        if(account == null)
        {
            return  "redirect:login";
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Room room = roomService.selectRoomById(id);

        room.setRoomType(roomTypeService.selectRoomTypeById(room.getRoomTypeId().longValue()));

        String start = sdf.format(new Date());
        List<RoomReserve> reserves = roomReserveService.selectRoomReserveListByRoomId(start,id);
        model.addAttribute("room",room);
        List<String> listdate = getDates(reserves);
        model.addAttribute("listdate", listdate);

        return "home/index/room_reserve";
    }

    @RequestMapping(value = "room_reserve_add", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult addRoomReserve(String startDate, String endDate, Integer id, Integer number)throws Exception
    {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Room room = roomService.selectRoomById(id);

        if(room.getIsTimeLimit() != Room.TimeLimit)
        {
            startDate = startDate + " 14:00:00";
            endDate = endDate + " 12:00:00";
        }

        if(room.getStatus() == Room.NORMAL)
        {
            return AjaxResult.error("房间不可用");
        }

        if(room.getIsTimeLimit() == Room.TimeLimit)
        {
            return AjaxResult.error("房间是钟点房");
        }


        Date start = null;
        Date end = null;
        try
        {
            start = sdf.parse(startDate);
            end = sdf.parse(endDate);
        }catch (Exception e)
        {
            return AjaxResult.error("时间格式错误");
        }

        //判断是否被预定
        if(roomReserveService.selectRoomReserveCount(id, startDate, endDate) > 0)
        {
            return AjaxResult.error("已被预定");
        }

        //判断用户选择是否超过了其他人的选择
        //找到最近的一个区间
        RoomReserve item = roomReserveService.selectStartSection(id, startDate);
        if(item != null) {

            Date databaseStart = sdf.parse(sdf.format(item.getStartDateTime()));
            if(end.compareTo(databaseStart) > 0)
            {
                return AjaxResult.error("已被预定");
            }
        }

        Account account = SessionUtil.getLogindeAccount();
        if(account == null)
        {
            return AjaxResult.error("请登录!");
        }

        //判断是否为空


        if(start.getTime() >= end.getTime())
        {
            return AjaxResult.error("开始时间大于结束时间!");
        }

        RoomReserve roomReserve = new RoomReserve();
        roomReserve.setAccountId(account.getId());
        roomReserve.setRoomId(id.longValue());
        roomReserve.setIsrate(RoomReserve.NO_RATE); //没有评分
        roomReserve.setNumber(number.longValue());
        roomReserve.setStartDateTime(start);
        roomReserve.setEndDateTime(end);

        if(roomReserveService.insertRoomReserve(roomReserve) == 0)
        {
            return AjaxResult.error("预定失败");
        }

        return toAjax(true);
    }

    //获取日期
    public List<String> getDates(List<RoomReserve> reserves)
    {
        SimpleDateFormat sdf_d = new SimpleDateFormat("yyyy-MM-dd");

        List<String> listDate = new ArrayList<>();
        for(RoomReserve roomReserve : reserves)
        {
            Date start = roomReserve.getStartDateTime();
            Date end = roomReserve.getEndDateTime();
            listDate.add(sdf_d.format(start));
            while(start.compareTo(end) < 0)
            {
                Calendar cal = Calendar.getInstance();
                cal.setTime(start);
                cal.add(Calendar.DAY_OF_MONTH, 1);
                start = cal.getTime();
                listDate.add(sdf_d.format(start));
            }
            listDate.remove(listDate.size()-1);
        }


        return listDate;
    }

    @RequestMapping("/room_reserve_timelimit")
    public String roomReserveTimeLimit(Model model, Integer id)throws Exception
    {
        Account account = SessionUtil.getLogindeAccount();
        if(account == null)
        {
            return  "redirect:login";
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Room room = roomService.selectRoomById(id);
        room.setRoomType(roomTypeService.selectRoomTypeById(room.getRoomTypeId().longValue()));
        model.addAttribute("room", room);

        String start = sdf.format(new Date());
        List<RoomReserve> reserves = roomReserveService.selectRoomReserveListByRoomId(start,id);
        List<String> listdate = getDayByTime(reserves);
        model.addAttribute("listdate", listdate);
        return "home/index/room_reserve_timelimit";
    }

    //找到当天的预定信息
    public static List<String> getDayByTime(List<RoomReserve> reserves)throws Exception
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<String> listdate = new ArrayList<>();
        for (RoomReserve item: reserves) {
            listdate.add(sdf.format(item.getStartDateTime()));
        }
        return listdate;
    }

    @RequestMapping(value = "room_reserve_timelimit_add", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult roomReserveTimeLimit(String startTime, String endTime, Integer id, Integer number, String date)
    {
        SimpleDateFormat sdf_df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date start = null;
        Date end = null;
        Date day = null;
        Date min = null;
        Date max = null;

        Room room = roomService.selectRoomById(id);
        if(room.getStatus() == Room.NORMAL)
        {
            return AjaxResult.error("房间不可用");
        }

        if(room.getIsTimeLimit() == Room.NOT_TimeLimit)
        {
            return AjaxResult.error("房间是普通房");
        }

        try
        {
            day = sdf_df.parse(date + " 00:00:00");
            start = sdf_df.parse(date + " " + startTime + ":00:00");
            end = sdf_df.parse(date + " " + endTime + ":00:00");
            min = sdf_df.parse(date + " 06:00:00");
            max = sdf_df.parse(date + " 18:00:00");
        }catch (Exception e)
        {
            return AjaxResult.error("时间格式错误");
        }

        if(start.compareTo(end) > 0)
        {
            return AjaxResult.error("开始时间大于结束时间");
        }

        if(min.getTime() > start.getTime() || max.getTime() < end.getTime())
        {
            return AjaxResult.error("钟点房预定必须在6~18点");
        }

        RoomReserve roomReserve = roomReserveService.selectEqualStartDate(id, date);
        if(roomReserve != null)
        {
            return AjaxResult.error("今天被其他人预定了");
        }


        Account account = SessionUtil.getLogindeAccount();
        if(account == null)
        {
            return AjaxResult.error("请登录!");
        }


        RoomReserve insert = new RoomReserve();
        insert.setAccountId(account.getId());
        insert.setRoomId(id.longValue());
        insert.setIsrate(RoomReserve.NO_RATE); //没有评分
        insert.setNumber(number.longValue());
        insert.setStartDateTime(start);
        insert.setEndDateTime(end);

        if(roomReserveService.insertRoomReserve(insert) == 0)
        {
            return AjaxResult.error("预定失败");
        }



        return toAjax(true);
    }

}
